﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LibraryMusicStore;

namespace MvcMusicStore.Models
{
    public partial class ShoppingCart
    {
        MusicStoreEntities storeDB = new MusicStoreEntities();
        string shoppingCartId { get; set; }
        public const string CartSessionKey = "CardId";

        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.shoppingCartId = cart.GetCartId(context);
            return cart;
        }

        public void AddToCart(Album album)
        {
            var cartItem = storeDB.Carts.SingleOrDefault(
                c => c.CartId == shoppingCartId &&
                    c.AlbumId == album.AlbumId);

            if (cartItem==null)
            {
                //create new cart item
                cartItem = new Cart
                {
                    AlbumId = album.AlbumId,
                    CartId = shoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };

                storeDB.Carts.InsertOnSubmit(cartItem);
            }
            else
            {
                //add one to quantity
                cartItem.Count++;
            }

            //save it
            storeDB.SubmitChanges();

        }

        public int ChangeQuantity(int id, int quantity)
        {
            //get the cart
            var cartItem = storeDB.Carts.SingleOrDefault(
                c => c.CartId == shoppingCartId &&
                    c.RecordId == id);

            //int itemCount = 0;

            if (cartItem != null)
            {
                cartItem.Count = quantity;
                //save 
                storeDB.SubmitChanges();
            }
            return quantity;
        }

        public void RemoveFromCart(int id)
        { 
            //get the cart
            var cartItem = storeDB.Carts.SingleOrDefault(
                c => c.CartId == shoppingCartId &&
                    c.RecordId == id);

            //int itemCount = 0;

            if (cartItem!=null)
            {
                storeDB.Carts.DeleteOnSubmit(cartItem);

                //save 
                storeDB.SubmitChanges();
            }
        }

        public void EmptyCart()
        {
            var cartItems = storeDB.Carts.Where(c => c.CartId == shoppingCartId);
            
            storeDB.Carts.DeleteAllOnSubmit(cartItems);
            storeDB.SubmitChanges();
        }

        public List<Cart> GetCartItems()
        {
            var cartItems = storeDB.Carts
                .Where(c => c.CartId == shoppingCartId)
                .ToList();

            return cartItems;
        }

        public int GetCount()
        {
            int? count = (from c in storeDB.Carts
                         where c.CartId == shoppingCartId
                         select (int?)c.Count).Sum();

            return count ?? 0;
        }

        public decimal GetTotal()
        {
            decimal? total = (from c in storeDB.Carts
                              where c.CartId == shoppingCartId
                              select (decimal?)c.Count*c.Album.Price).Sum();

            return total ?? decimal.Zero;
        }

        public void CreateOrder(Order order)
        {
            //decimal orderTotal = 0;
            var cartItems = GetCartItems();

            //iterate the items in the cart, adding order details for it
            foreach (var carItem in cartItems)
            {
                var oderDetail = new OrderDetail
                {
                    OrderId = order.OrderId,
                    AlbumId = carItem.AlbumId,
                    Quantity = carItem.Count,
                    UnitPrice = carItem.Album.Price * (1 + storeDB.VATs.First().Value / 100)
                };

                storeDB.OrderDetails.InsertOnSubmit(oderDetail);

                //orderTotal+=(carItem.Count*carItem.Album.Price);
            }

            //save
            storeDB.SubmitChanges();

            //empty the shopping cart
            EmptyCart();

            //return the orderid as a confirmation number

            //return orderTotal;
        }

        private string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrEmpty(context.User.Identity.Name))
                {
                    // User is logged in, associate the cart with there username 
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {
                    //Generate a new random GUID using System.Guid class
                    Guid tempCartId = new Guid();

                    //Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }

        // When a user has logged in, migrate their shopping cart to 
        // be associated with their username 
        public void MigrateCart(string userName)
        {
            var shoppingCart = storeDB.Carts
                .Where(c => c.CartId == shoppingCartId);

            foreach (Cart item in shoppingCart)
            {
                item.CartId = userName;
            }
            
            storeDB.SubmitChanges();
        }
    }
}
